package com.example.serverSide.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.serverSide.commom.dto.DeptAccess;
import com.example.serverSide.mapper.MenuCheckMapper;
import com.example.serverSide.mapper.SysDeptMapper;
import com.example.serverSide.pojo.MenuCheck;
import com.example.serverSide.pojo.SysDept;
import com.example.serverSide.service.MenuCheckService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MenuCheckServiceImpl extends ServiceImpl<MenuCheckMapper, MenuCheck> implements MenuCheckService {
    @Autowired
    MenuCheckMapper menuCheckMapper;
    @Autowired
    SysDeptMapper systemDeptMapper;
    @Override
    public String updateAccess(DeptAccess deptAccess) {
        Long deptId = 0L;
        if(deptAccess.getId() != null) {
            LambdaQueryWrapper<MenuCheck> queryWrapper = new LambdaQueryWrapper<>();
            deptId = deptAccess.getId();
            queryWrapper.eq(MenuCheck::getDeptId, deptId);
            SysDept sysDept = new SysDept();
            sysDept.setId(deptId);
            sysDept.setName(deptAccess.getDeptName());
            systemDeptMapper.updateById(sysDept);
            menuCheckMapper.delete(queryWrapper);
        }else {
            SysDept sysDept = new SysDept();
            sysDept.setName(deptAccess.getDeptName());
            systemDeptMapper.insert(sysDept);
            LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysDept::getName,deptAccess.getDeptName());
            SysDept newSysDept = systemDeptMapper.selectOne(queryWrapper);
            deptId = newSysDept.getId();
        }
        List<Long> menuIds = deptAccess.getMenuIds();
        for (Long menuid : menuIds){
            MenuCheck check = new MenuCheck();
            check.setMenuId(menuid);
            check.setDeptId(deptId);
            menuCheckMapper.insert(check);
        }
        return "更改成功";
    }

    @Override
    public void deleteByDeptId(String id) {
        LambdaQueryWrapper<MenuCheck> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MenuCheck::getDeptId, id);
        menuCheckMapper.delete(queryWrapper);
    }
}
